#ifndef USERCOMMON_C
#define USERCOMMON_C
#include <math.h>
#include <string.h>
#include "userstruct.h"

//gcc usercommon.c -c -o usercommon.o -lm

#pragma region 公共函数定义 
//计算两个WeekSecTimeA之间的秒数差
double delt_WeekSecT(WeekSecTimeA *_t1,WeekSecTimeA *_t2)
{
    return ( _t1->Week-_t2->Week)*604800 + _t1->Secs - _t2->Secs;
}

/*
    初始化CGS2000坐标系定义的有关参数
    返回：   0：正确读取       非0：不正常读取
    改动记录：所有坐标系的定义已经参考最新的CGCS2000定义的物理参数
*/
int  GetReadCGS2000Para(CGS2000_PAR  *mCGS2000Para)
{
    strcpy(mCGS2000Para->refname,"CGCS2000");
    mCGS2000Para->GM = 3986004.418e8;
    mCGS2000Para->earthmass = 5.97333196e+24;
    mCGS2000Para->omega_earth = 7292115.0e-11;
    mCGS2000Para->eartha = 6378137.0;
    mCGS2000Para->flat = 1.0/298.257222101;
    mCGS2000Para->vlight =  299792458;
    mCGS2000Para->earthb = 6356752.3141;
    return 0;
}

// Fractional part of a number (y=x-[x])
double Frac(double x)
{
    return x-floor(x);
}
// x mod y
double Modulo(double x, double y)
{
    return y*Frac(x/y);
}
//------------------------------------------------------------------------------
// EccAnom
// Purpose:
// Computes the eccentric anomaly for elliptic orbits
// Input/Output:
//   M         Mean anomaly in [rad]
//   e         Eccentricity of the orbit [0,1[
//   <return>  Eccentric anomaly in [rad]
//------------------------------------------------------------------------------
double EccAnom (double M, double e)
{
    // Constants
    const int maxit = 15;
    const double eps = 1.0E-14;
    // Variables
    int    i=0;
    double E, f;
    // Starting value
    M = Modulo(M, 2.0*pi);
    if (e<0.8) E=M; else E=pi;
    // Iteration
    do {
        f = E - e*sin(E) - M;
        E = E - f / ( 1.0 - e*cos(E) );
        ++i;
        if (i==maxit) {
            //cerr << " convergence problems in EccAnom" << endl;
            break;
        }
    }
    while (fabs(f) > eps);
    return E;
}

/*将时间表达形式规范化*/
void WeekSecTimeA_validity(WeekSecTimeA *_tm)
{
    while (_tm->Secs >= 7.0*86400)
    {
        _tm->Secs -= 7.0*86400;
        _tm->Week += 1;
    }
    while (_tm->Secs < 0)
    {
        _tm->Secs += 7.0*86400;
        _tm->Week -= 1;
    }
}
#pragma endregion

#endif //USERCOMMON_C